<template>
  <div>
    <div>
      <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :formType="type" :isSubmitBtn="false" @formChange="formChangeHandle" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton v-if="type !== 'show'" type="primary" :click="saveDialog">保 存</AjaxButton>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { updatePartPriceAdjust } from '@/api/part/inventoryManager/partPriceAdjust';
import { setTimeout } from 'timers';
import { debuglog } from 'util';
// import { findStorageCode } from '@/api/repair/basicParameters';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { isAuthorized } from '@/utils/index';

export default {
  name: 'BrandModal',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.saveData = null;
    return {
      formList: this.createFormList()
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    },
    // 价格保留类型
    priceKeepType() {
      return this.formList.find(item => item.fieldName == 'rond').initialValue;
    },
    // 基准价
    latestPrices() {
      return this.formList.find(item => item.fieldName == 'latestPrices').initialValue;
    },
    // 调整价
    salesPrices() {
      return this.formList.find(item => item.fieldName == 'salesPrices').initialValue;
    }
  },
  watch: {
    latestPrices: {
      handler() {
        this.salesPriceChange();
      }
    },
    salesPrices: {
      handler() {
        this.salesPriceChange();
      }
    }
    // priceKeepType(newVal, oldVal) {
    //   console.log(newVal);
    //   let type = 2;
    //   switch (newVal) {
    //     case 80651001:
    //       type
    //   }
    // }
  },
  mounted() {
    this.getStorage();
    this.init();
    this.getSystemAuthority();
  },
  created() {},
  methods: {
    init() {
      if (this.type === 'edit') {
        console.log(this.rowData, 'rowdata');
        // 更新接口需要的记录 ID
        this.formList.find(x => x.fieldName === 'isCostType').itemList = [
          { value: 80501002, text: '销售价' }
          // { value: 80501004, text: '网点价' },
          // { value: 80501007, text: '终端建议零售价格' }
        ];
        this.recordId = this.rowData.storageCode;
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
        this.formList.find(x => x.fieldName === 'baseCostType').initialValue = 80501005;
        this.formList.find(x => x.fieldName === 'latestPrices').initialValue = this.rowData.latestPrice; // 基准价
        this.formList.find(x => x.fieldName === 'isCostType').initialValue = 80501002;
        this.formList.find(x => x.fieldName === 'markupPercentage').initialValue = 1;
        let markupPercentage = this.formList.find(x => x.fieldName === 'markupPercentage').initialValue; // 价格系数
        let latestPrices = this.formList.find(x => x.fieldName === 'latestPrices').initialValue; // 基准价
        // 调整价 = 基准价 * 价格系数
        let salesPrices = markupPercentage * latestPrices;
        this.formList.find(x => x.fieldName === 'salesPrices').initialValue = salesPrices; // 调整价
      }
    },

    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请选择',
          readonly: true,
          disabled: true,
          itemList: [],
          rules: [{ required: false, message: '请选择仓库', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          rules: [{ required: false, message: '请输入配件代码', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          rules: [{ required: false, message: '请输入配件名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'partGroupCode',
          placeholder: '请选择',
          readonly: true,
          disabled: true,
          itemList: this.createDictList('8075'),
          rules: [{ required: false, message: '请选择类别', trigger: 'change' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '索赔价',
        //   fieldName: 'claimPrice',
        //   placeholder: '请输入...',
        //   readonly: true,
        //   disabled: true,
        //   rules: [{ required: false, message: '请输入索赔价', trigger: 'blur' }]
        // },
        {
          type: 'INPUT',
          label: '最新进货价',
          fieldName: 'latestPrice',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          rules: [{ required: false, message: '请输入最新进货价', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'storagePositionCode',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          rules: [{ required: false, message: '请输入库位', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '销售价',
          fieldName: 'salesPrice',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          rules: [{ required: false, message: '请输入销售价', trigger: 'blur' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '网点价',
        //   fieldName: 'nodePrice',
        //   readonly: true,
        //   disabled: true
        // },
        {
          type: 'SELECT',
          label: '基准价类型',
          fieldName: 'baseCostType',
          placeholder: '请选择',
          itemList: this.createDictList('8050'),
          change: this.baseCostTypeChange,
          rules: [{ required: false, message: '请选择基准价类型', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '基准价',
          fieldName: 'latestPrices',
          placeholder: '请输入...',
          readonly: true,
          disabled: true,
          precision: 2,
          rules: [{ required: false, message: '请输入基准价', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'markupPercentage',
          precision: 2,
          placeholder: '请输入...',
          hidden: true,
          change: val => this.markupChange(val),
          rules: [{ required: false, message: '请输入价格系数', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '调整价类型',
          fieldName: 'isCostType',
          placeholder: '请选择',
          itemList: [],
          change: () => this.isCostTypeChange(),
          rules: [{ required: false, message: '请选择调整价类型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '调整价',
          fieldName: 'salesPrices',
          placeholder: '请输入...',
          change: val => this.salesPriceChange(val),
          rules: [{ required: true, message: '请输入调整价', trigger: 'blur' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '终端建议零售价格',
        //   fieldName: 'insurancePrice',
        //   placeholder: '请输入...',
        //   readonly: true,
        //   disabled: true,
        //   rules: [{ required: false, message: '请输入终端建议零售价格', trigger: 'blur' }]
        // },
        {
          type: 'SELECT',
          label: '调整价格四舍五入',
          fieldName: 'rond',
          placeholder: '请选择',
          itemList: this.createDictList('8065'),
          change: e => this.rondChange(e),
          rules: [{ required: false, message: '请选择调整价格四舍五入', trigger: 'change' }]
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },

    async getStorage() {
      const res = await getStroageList();
      this.formList.find(x => x.fieldName === 'storageCode').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE + '' }));
    },

    async saveDialog() {
      // debugger;
      this.$refs.formPanel.SUBMIT_FORM();
      // isCostType  调整价格类型
      // salesPrices  调整价
      // rond    调整价四舍五入
      // baseCostType  基准类型
      console.log(this.saveData, 'savedata');
      if (this.saveData !== null) {
        let isCostType = this.saveData.isCostType;
        let salesPrices = this.saveData.salesPrices;
        let rond = this.saveData.rond || null;
        let baseCostType = this.saveData.baseCostType;
        let storageCode = this.rowData.storageCode;
        let partNo = this.rowData.partNo;
        if (Number(salesPrices) < Number(this.saveData.latestPrice)) {
          this.$notify({
            title: '警告',
            message: '调整价不能小于最新进货价！',
            type: 'warning'
          });
          return;
        }
        // if (Number(salesPrices) > Number(this.rowData.limitPrice)) {
        //   this.$notify({
        //     title: '警告',
        //     message: '调整价超过销售限价限制调整！',
        //     type: 'warning'
        //   });
        //   return;
        // }
        let obj = {
          isCostType,
          salesPrices,
          rond,
          baseCostType,
          STORAGE_CODE: storageCode,
          PART_NO: partNo
        };
        console.log(obj, 'obj');
        let res = await updatePartPriceAdjust(obj);
        console.log(res);
        if (res.resultCode == '200') {
          this.test();
        }
      }
    },

    closeDialog(param) {
      this.$emit('close', false, param);
    },
    test() {
      this.$notify({
        title: '成功',
        message: '成功',
        type: 'success'
      });
      this.closeDialog('refresh');
    },

    baseCostTypeChange(e) {
      console.log(e);
      let latestPricesItem = this.formList.find(x => x.fieldName === 'latestPrices');
      let isCostTypeItem = this.formList.find(x => x.fieldName === 'isCostType');
      switch (e) {
        case 80501001:
          latestPricesItem.initialValue = this.rowData.costPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501002:
          latestPricesItem.initialValue = this.rowData.salesPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501003:
          latestPricesItem.initialValue = this.rowData.claimPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501004:
          latestPricesItem.initialValue = this.rowData.nodePrice || 0;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501005:
          latestPricesItem.initialValue = this.rowData.latestPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501006:
          latestPricesItem.initialValue = this.rowData.outPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501007:
          latestPricesItem.initialValue = this.rowData.insurancePrice;
          isCostTypeItem.itemList = [{ value: 80501002, text: '销售价' }];
          break;
        case 80501008:
          latestPricesItem.initialValue = this.rowData.instructPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
        case 80501009:
          latestPricesItem.initialValue = this.rowData.limitPrice;
          isCostTypeItem.itemList = [
            { value: 80501002, text: '销售价' }
            // { value: 80501004, text: '网点价' },
            // { value: 80501007, text: '终端建议零售价格' }
          ];
          break;
      }
      this.formList = [...this.formList];
    },

    isCostTypeChange() {
      this.$nextTick(() => {
        if (this.formList.find(x => x.fieldName === 'baseCostType').initialValue == 80501002) {
          this.formList.find(x => x.fieldName === 'salesPrices').initialValue = this.rowData.salesPrice;
        } else if (this.formList.find(x => x.fieldName === 'baseCostType').initialValue == 80501004) {
          this.formList.find(x => x.fieldName === 'salesPrices').initialValue = this.rowData.nodePrice;
        } else if (this.formList.find(x => x.fieldName === 'baseCostType').initialValue == 80501007) {
          this.formList.find(x => x.fieldName === 'salesPrices').initialValue = this.rowData.insurancePrice;
        }
        this.formList = [...this.formList];
      });
    },
    salesPriceChange(val) {
      let latestPrices = this.formList.find(x => x.fieldName === 'latestPrices').initialValue; // 基准价
      let salesPrices = this.formList.find(item => item.fieldName == 'salesPrices').initialValue; // 调整价
      if (latestPrices && !salesPrices) {
        salesPrices = latestPrices;
        this.formList.find(item => item.fieldName == 'salesPrices').initialValue = latestPrices;
      }
      if (!latestPrices) {
        // this.$notify({
        //   title: '警告',
        //   message: '基准价等于0，无法修改价格系数！',
        //   type: 'error'
        // });
        // this.formList.find(x => x.fieldName == 'salesPrices').initialValue = 0;
      } else {
        let markupPercentage = salesPrices / latestPrices;
        if (isNaN(markupPercentage)) {
          a = 0;
        }
        this.formList.find(x => x.fieldName === 'markupPercentage').initialValue = markupPercentage;
      }
      this.formList = [...this.formList];
    },

    rondChange(e) {
      this.$nextTick(() => {
        let adjustPriceObj = this.formList.find(item => item.fieldName == 'salesPrices');
        let initPrice = Number(adjustPriceObj.initialValue);
        switch (e) {
          case 80651001: // 元
            adjustPriceObj.initialValue = initPrice.toFixed(0);
            adjustPriceObj.precision = 0;
            break;
          case 80651002: // 角
            adjustPriceObj.initialValue = initPrice.toFixed(1);
            adjustPriceObj.precision = 1;
            break;
          case 80651003: // 分
            adjustPriceObj.initialValue = initPrice.toFixed(2);
            adjustPriceObj.precision = 2;
            break;
        }
      });
    },

    markupChange(val) {
      let latestPrices = this.formList.find(x => x.fieldName === 'latestPrices').initialValue; // 基准价
      // 调整价 = 基准价 * 价格系数
      let salesPrices = val * latestPrices;
      if (isNaN(salesPrices)) {
        salesPrices = 0.0;
      }
      let newSalesPrices = parseFloat(salesPrices).toFixed(4);
      // console.log(newSalesPrices, 'newSalesPrices');
      if (this.formList.find(x => x.fieldName === 'rond').initialValue == 80651001) {
        this.formList.find(x => x.fieldName === 'salesPrices').initialValue = Math.round(newSalesPrices);
      } else if (this.formList.find(x => x.fieldName === 'rond').initialValue == 80651002) {
        this.formList.find(x => x.fieldName === 'salesPrices').initialValue = Math.round(newSalesPrices * 10) / 10;
      } else if (this.formList.find(x => x.fieldName === 'rond').initialValue == 80651003) {
        this.formList.find(x => x.fieldName === 'salesPrices').initialValue = Math.round(newSalesPrices * 100) / 100;
      } else {
        this.formList.find(x => x.fieldName === 'salesPrices').initialValue = Math.round(newSalesPrices * 100) / 100;
      }
      this.formList = [...this.formList];
    },

    // 获取系统权限
    getSystemAuthority() {
      // 保修信息
      console.log('11111------------');
      let flagResult = isAuthorized('1313', '13131009');
      console.log(flagResult, 'flagResult');
      if (flagResult) {
        console.log('13131009');
        this.formList.find(x => x.fieldName === 'markupPercentage').hidden = false;
      } else {
        console.log('1313100913131009--------------');
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
